/*
 * buffer.cpp
 *
 *  Created on: 06.04.2010
 *      Author: Florian Gref
 */
#include"buffer.h"

Buffer::Buffer(char* src) {
	this->buffer1 = new char[BUFFER_SIZE];
	this->buffer2 = new char[BUFFER_SIZE];
	this->bufferLoaded = false;
	this->endOfFile = false;
	this->position = 0;
	this->current_ptr = NULL;

	if ((this->src_ptr = fopen(src, "r")) == NULL) {
		perror("Unable to open the sourcefile, Buffer");
	} else {
		load();
		if (this->endOfFile) {
			std::cout << "\nEOF reached, Buffer loaded.\n";
		} else {
			std::cout << "\nBuffer loaded successfully.\n";
		}

	}

}

void Buffer::load() {
	fseek(src_ptr, 0, SEEK_END);
	this->src_size = ftell(src_ptr);
	std::cout << "The file, you've opened consists of " << src_size
			<< " characters";
	rewind(src_ptr);

	this->endOfFile = (fread(buffer1, 1, BUFFER_SIZE, this->src_ptr)
			< (unsigned int) BUFFER_SIZE);
	this->current_ptr = this->buffer1;
}

char Buffer::getChar() {
	if (changeBuffer()) {
		this->endOfFile = (fread(current_ptr, 1, BUFFER_SIZE, this->src_ptr)
				< (unsigned int) BUFFER_SIZE);
		std::cout << "[LOAD]";
	}
	return current_ptr[position++];

}

bool Buffer::changeBuffer() {
	bool result = false;
	if (position == BUFFER_SIZE) {
		result = true;
		if (current_ptr == buffer1) {
			std::cout << "[Buffer 2]";
			current_ptr = buffer2;
			this->bufferLoaded = true;
		} else {
			current_ptr = buffer1;
			std::cout << "[Buffer 1]";
		}
		position = 0;
	}
	return result;
}


void Buffer::ungetChar() {
	if (position == 0 && (!this->bufferLoaded)) {
		perror("Unable to go back!!!");
	} else {
		if (position > 0) {
			position--;
		} else {
			if (current_ptr == buffer1) {
				current_ptr = buffer2;
			} else {
				current_ptr = buffer1;
			}
			position = BUFFER_SIZE - 1;
		}
	}
}
